package com.xxl.sso.core.store;

import com.xxl.sso.core.user.XxlSsoUser;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * make client sessionId
 * <p>
 * client: cookie = [userid#version]
 * server: redis
 * key = [userid]
 * value = user (user.version, valid this)
 * <p>
 * //   group         The same group shares the login status, Different groups will not interact
 *
 * @author xuxueli 2018-11-15 15:45:08
 */

public class SsoSessionIdHelper {


    /**
     * make client sessionId
     *
     * @param xxlSsoUser
     * @return
     */
    public static String makeSessionId(XxlSsoUser xxlSsoUser) {
        return xxlSsoUser.getUserid().concat("_").concat(xxlSsoUser.getVersion());
    }

    /**
     * parse storeKey from sessionId
     *
     * @param sessionId
     * @return
     */
    public static String parseStoreKey(String sessionId) {
        if (sessionId != null && sessionId.contains("_")) {
            return sessionId;
        }
        return null;
    }

    public static String parseUserId(String sessionId) {
        if (sessionId != null && sessionId.contains("_")) {
            String[] sessionIdArr = sessionId.split("_");
            if (sessionIdArr.length == 2
                    && sessionIdArr[0] != null
                    && !sessionIdArr[0].trim().isEmpty()) {
                return sessionIdArr[0].trim();
            }
        }
        return null;
    }

    /**
     * parse version from sessionId
     *
     * @param sessionId
     * @return
     */
    public static String parseVersion(String sessionId) {
        if (sessionId != null && sessionId.contains("_")) {
            String[] sessionIdArr = sessionId.split("_");
            if (sessionIdArr.length == 2
                    && sessionIdArr[1] != null
                    && !sessionIdArr[1].trim().isEmpty()) {
                return sessionIdArr[1].trim();
            }
        }
        return null;
    }

    public static Long extractUseIdFromSessionId(String sessionId) {
        Pattern pattern = Pattern.compile("xxl_sso_sessionid#(\\d+)_");
        Matcher matcher = pattern.matcher(sessionId);
        if (matcher.find()) {
            String userId = matcher.group(1);
            return Long.parseLong(userId);
        }
        return null;
    }
}
